package com.wx;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Stream;

public class Test_01 {
    public static void main(String[] args) throws IOException {
        /**
         * 获得用户上传的连接
         * 截取字符串获取项目的名字
         * 方便切换目录
         */
        excuteShell("https://gitee.com/wxLogic/autotest.git","cccccmm","autotest");
    }

    /**
     * @param repositoryPath 仓库地址
     * @param path UUID生成
     * @param projectName 项目名字 通过截取仓库地址获得i
     * @throws IOException
     */
    public static void excuteShell(String repositoryPath,String path,String projectName) throws IOException {
        // 通过SSH2协议远程与linux建立连接
        Connection con = new Connection("192.168.23.129",22);
        Session session=null;
        //建立连接
        con.connect();
        //登录系统
        boolean b = con.authenticateWithPassword("root", "root");
        if(b){
            // 获得连接
             session = con.openSession();
            // 执行脚本
            session.execCommand("bash /auto.sh "+repositoryPath+" "+path+" "+projectName);
            StreamGobbler gobbler = new StreamGobbler(session.getStdout());
            BufferedReader reader = new BufferedReader(new InputStreamReader(gobbler));
            // 获得脚本执行的结果
            Stream<String> lines = reader.lines();
            lines.forEach(s-> System.out.println(s));
            // 0成功 非0失败
            System.out.println("result："+session.getExitStatus());
            session.close();
            con.close();
        }else {
            // 连接失败
            System.out.println("与服务器连接失败");
        }
    }
}
